package com.upup.train_management.controller;

import com.upup.train_management.entity.Ticket;
import com.upup.train_management.entity.User;
import com.upup.train_management.service.TicketService;
import com.upup.train_management.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/tickets")
public class TicketController {

    private final TicketService ticketService;
    private final UserService userService;

    @Autowired
    public TicketController(TicketService ticketService, UserService userService) {
        this.ticketService = ticketService;
        this.userService = userService;
    }

    @GetMapping
    public ResponseEntity<List<Ticket>> getAllTickets() {
        // 只有管理员能查看所有票据
        User currentUser = getCurrentUser();
        if (currentUser != null && "ADMIN".equals(currentUser.getUserRole())) {
            return ResponseEntity.ok(ticketService.getAllTickets());
        }
        return ResponseEntity.status(403).build();
    }

    @GetMapping("/{id}")
    public ResponseEntity<Ticket> getTicketById(@PathVariable Long id) {
        Ticket ticket = ticketService.getTicketById(id);
        if (ticket == null) {
            return ResponseEntity.notFound().build();
        }

        // 验证用户只能查看自己的票
        User currentUser = getCurrentUser();
        if (currentUser == null || (!isAdmin(currentUser) && !ticket.getUserId().equals(currentUser.getId()))) {
            return ResponseEntity.status(403).build();
        }

        return ResponseEntity.ok(ticket);
    }

    @GetMapping("/number/{ticketNumber}")
    public ResponseEntity<Ticket> getTicketByNumber(@PathVariable String ticketNumber) {
        Ticket ticket = ticketService.getTicketByNumber(ticketNumber);
        if (ticket == null) {
            return ResponseEntity.notFound().build();
        }

        // 验证用户只能查看自己的票
        User currentUser = getCurrentUser();
        if (currentUser == null || (!isAdmin(currentUser) && !ticket.getUserId().equals(currentUser.getId()))) {
            return ResponseEntity.status(403).build();
        }

        return ResponseEntity.ok(ticket);
    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<List<Ticket>> getTicketsByUserId(@PathVariable Long userId) {
        // 验证用户只能查看自己的票
        User currentUser = getCurrentUser();
        if (currentUser == null || (!isAdmin(currentUser) && !userId.equals(currentUser.getId()))) {
            return ResponseEntity.status(403).build();
        }

        return ResponseEntity.ok(ticketService.getTicketsByUserId(userId));
    }

    @GetMapping("/schedule/{scheduleId}")
    public ResponseEntity<List<Ticket>> getTicketsByScheduleId(@PathVariable Long scheduleId) {
        // 只有管理员能按车次查询票据
        User currentUser = getCurrentUser();
        if (currentUser != null && isAdmin(currentUser)) {
            return ResponseEntity.ok(ticketService.getTicketsByScheduleId(scheduleId));
        }
        return ResponseEntity.status(403).build();
    }

    @GetMapping("/my-tickets")
    public ResponseEntity<List<Ticket>> getMyTickets() {
        User currentUser = getCurrentUser();
        if (currentUser == null) {
            return ResponseEntity.status(401).build();
        }

        return ResponseEntity.ok(ticketService.getTicketsByUserId(currentUser.getId()));
    }

    @GetMapping("/my-tickets/status/{status}")
    public ResponseEntity<List<Ticket>> getMyTicketsByStatus(@PathVariable String status) {
        User currentUser = getCurrentUser();
        if (currentUser == null) {
            return ResponseEntity.status(401).build();
        }

        return ResponseEntity.ok(ticketService.getTicketsByUserAndStatus(currentUser.getId(), status));
    }

    @PostMapping
    public ResponseEntity<Ticket> createTicket(@RequestBody Ticket ticket) {
        User currentUser = getCurrentUser();
        if (currentUser == null) {
            return ResponseEntity.status(401).build();
        }

        // 设置当前用户ID
        ticket.setUserId(currentUser.getId());

        return ResponseEntity.ok(ticketService.createTicket(ticket));
    }

    @PutMapping("/{id}")
    public ResponseEntity<Ticket> updateTicket(@PathVariable Long id, @RequestBody Ticket ticket) {
        Ticket existingTicket = ticketService.getTicketById(id);
        if (existingTicket == null) {
            return ResponseEntity.notFound().build();
        }

        // 验证用户权限
        User currentUser = getCurrentUser();
        if (currentUser == null || (!isAdmin(currentUser) && !existingTicket.getUserId().equals(currentUser.getId()))) {
            return ResponseEntity.status(403).build();
        }

        ticket.setId(id);
        return ResponseEntity.ok(ticketService.updateTicket(ticket));
    }

    @PutMapping("/{id}/cancel")
    public ResponseEntity<Void> cancelTicket(@PathVariable Long id) {
        Ticket ticket = ticketService.getTicketById(id);
        if (ticket == null) {
            return ResponseEntity.notFound().build();
        }

        // 验证用户权限
        User currentUser = getCurrentUser();
        if (currentUser == null || (!isAdmin(currentUser) && !ticket.getUserId().equals(currentUser.getId()))) {
            return ResponseEntity.status(403).build();
        }

        boolean cancelled = ticketService.cancelTicket(id);
        if (cancelled) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.badRequest().build();
        }
    }    private User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated() || 
            "anonymousUser".equals(authentication.getName())) {
            return null;
        }
        
        User user = userService.getUserByUsername(authentication.getName());
        // 额外验证：确保用户对象有效且有必要的字段
        if (user == null || user.getUsername() == null || user.getUsername().isEmpty()) {
            return null;
        }
        
        return user;
    }

    private boolean isAdmin(User user) {
        return "ADMIN".equals(user.getUserRole());
    }
}